package io.github.jyrmc.deploy.utils

/**
 * host校验
 *
 * @author jy
 * @since 2023/5/15 22:24
 **/
object HostUtils {

    /**
     * 校验域名是否合法
     * @param host 目标服务器host
     * @return
     */
    fun validateHost(host: String): Boolean {
        val ipV4Regex = Regex("^(([0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])(\\.(?!$)|$)){4}$")
        if (host.count { it == '.' } > 2 && !ipV4Regex.matches(host)) {
            throw RuntimeException("HOST (property in ssh gradle plugin) [$host] is NOT VALID IPv4")
        } else {
            val domainNameRegex =
                Regex("^(((?!\\-))(xn\\-\\-)?[a-z0-9\\-_]{0,61}[a-z0-9]{1,1}\\.)*(xn\\-\\-)?([a-z0-9\\-]{1,61}|[a-z0-9\\-]{1,30})\\.[a-z]{2,}\$")
            if (!domainNameRegex.matches(host)) {
                throw RuntimeException("Domain name (host property in ssh gradle plugin) [$host] is NOT VALID DOMAIN")
            }
        }
        return true
    }
}